package cn.genmer.test.security.algorithm.similarity.lcs;

/**
 * Longest Common Subsequence eedleman／Wunsch算法
 */
public class LCS {
	
	public static void LCSLength(final int[][] c,final String[][] b, String[] X,String[] Y){
		int m = X.length;
		int n = Y.length;
		for(int i = 1; i <= m;i++){
			c[i][0] = 0;
		}
		for(int i = 1; i <= n; i++){
			c[0][i] = 0;
		}
		
		for(int i = 1; i <= m; i++){
			for(int j = 1; j <= n; j++){
				if(X[i-1].equals(Y[j-1])){
					c[i][j] = c[i-1][j-1]+1;
					b[i][j] = "\\";
				}else {
					if(c[i-1][j] >= c[i][j-1]){
						c[i][j] = c[i-1][j];
						b[i][j] = "|";
					}else{
						c[i][j] = c[i][j-1];
						b[i][j] = "-";
					}
				}
			}
		}
		
	}
	public static boolean PrintLCS(String[][] b,String[] X,int i,int j){
		if(i==0||j==0){
			return false;
		}
		if(b[i][j].equals("\\")){
			PrintLCS(b, X, i-1, j-1);
			System.out.print(X[i-1]+" ");
		}
		else if(b[i][j].equals("|")){
			PrintLCS(b, X, i-1, j);
		}
		else {
			PrintLCS(b, X, i, j-1);
		}
		return true;
	}
	public static void main(String[] args){
		String str1 = "高英路";
		String str2 = "高英路";
		String[] X = str1.split("");
		String[] Y = str2.split("");
		int m = X.length+1;
		int n = Y.length+1;
		int[][] c = new int[m][n];
		String[][] b = new String[m][n];
		LCSLength(c, b, X, Y);
		/*
		for(int i = 0; i < m; i++){
			for(int j = 0 ; j < n; j++){
				System.out.print(b[i][j]+"\t");
			}
			System.out.println();
		}
		*/
		PrintLCS(b, X, m-1, n-1);
	}

}
/*
xzyzzyx
zxyyzxz
MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCALLAAQANKESSSESFISRLLAIVAD
MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCTLLAAQANKENSNESFISRLLAIVAG 
*/
